// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/common/base/selectivity_info.h>
#include <pollux/expression/function_call_to_special_form.h>
#include <pollux/expression/special_form.h>

namespace kumo::pollux::exec {
    constexpr const char *kAnd = "and";
    constexpr const char *kOr = "or";

    class ConjunctExpr : public SpecialForm {
    public:
        ConjunctExpr(TypePtr type, std::vector<ExprPtr> &&inputs,
            bool isAnd,
            bool inputsSupportFlatNoNullsFastPath)
            : SpecialForm(
                  std::move(type),
                  std::move(inputs),
                  isAnd ? kAnd : kOr,
                  inputsSupportFlatNoNullsFastPath,
                  false /* trackCpuUsage */),
              isAnd_(isAnd) {
            selectivity_.resize(inputs_.size());
            inputOrder_.resize(inputs_.size());
            std::iota(inputOrder_.begin(), inputOrder_.end(), 0);

            std::vector<TypePtr> inputTypes;
            inputTypes.reserve(inputs_.size());
            std::transform(
                inputs_.begin(),
                inputs_.end(),
                std::back_inserter(inputTypes),
                [](const ExprPtr &expr) { return expr->type(); });

            // Apply type checking.
            resolveType(inputTypes);
        }

        void evalSpecialForm(
            const SelectivityVector &rows,
            EvalCtx &context,
            VectorPtr &result) override;

        bool isConditional() const override {
            return true;
        }

        const SelectivityInfo &selectivityAt(int32_t index) {
            return selectivity_[inputOrder_[index]];
        }

        std::string toSql(
            std::vector<VectorPtr> *complexConstants = nullptr) const override;

        void clearCache() override {
            Expr::clearCache();
            tempValues_.reset();
            tempNulls_.reset();
        }

    private:
        static TypePtr resolveType(const std::vector<TypePtr> &argTypes);

        void computePropagatesNulls() override {
            propagatesNulls_ = false;
        }

        void maybeReorderInputs();

        void updateResult(
            BaseVector *inputResult,
            EvalCtx &context,
            FlatVector<bool> *result,
            SelectivityVector *activeRows);

        bool evaluatesArgumentsOnNonIncreasingSelection() const override {
            return isAnd_;
        }

        // true if conjunction (and), false if disjunction (or).
        const bool isAnd_;

        // temp space for nulls and values of inputs
        BufferPtr tempValues_;
        BufferPtr tempNulls_;
        bool reorderEnabledChecked_ = false;
        bool reorderEnabled_;
        std::vector<SelectivityInfo> selectivity_;
        std::vector<int32_t> inputOrder_;

        friend class ConjunctCallToSpecialForm;
    };

    class ConjunctCallToSpecialForm : public FunctionCallToSpecialForm {
    public:
        explicit ConjunctCallToSpecialForm(bool isAnd)
            : FunctionCallToSpecialForm(), isAnd_(isAnd) {
        }

        TypePtr resolveType(const std::vector<TypePtr> &argTypes) override;

        ExprPtr constructSpecialForm(
            const TypePtr &type,
            std::vector<ExprPtr> &&compiledChildren,
            bool trackCpuUsage,
            const core::QueryConfig &config) override;

    private:
        bool isAnd_;
    };
} // namespace kumo::pollux::exec
